﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DiaosFix.Web.MVC.Models;

namespace DiaosFix.Web.MVC.Controllers
{
    public class ProfileController : Controller
    {
        private DiaosFix.Core.UsersOperator uo = new Core.UsersOperator();
        //
        // GET: /Profile/

        [Authorize]
        public ActionResult Index()
        {
            var userResponse = uo.FindUser(User.Identity.Name);
            if (userResponse.IsSuccess)
            {
                ViewBag.QueryTime = DateTime.Now;
            }
            else
            {
                ViewBag.ErrorMessage = userResponse.Message;
            }
            return View(userResponse.Item);
        }

        [Authorize]
        public ActionResult Edit()
        {
            var userResponse = uo.FindUser(User.Identity.Name);
            if (userResponse.IsSuccess)
            {
                ViewBag.Address = userResponse.Item.Address;
                ViewBag.ContactNumber = userResponse.Item.ContactNumber;
                ViewBag.Email = userResponse.Item.Email;
                ViewBag.RealName = userResponse.Item.RealName;
            }
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult Edit(EditProfileModel model)
        {
            if (ModelState.IsValid)
            {
                var userResponse = uo.FindUser(User.Identity.Name);
                if (userResponse.IsSuccess)
                {
                    var user = userResponse.Item;
                    user.Address = model.Address;
                    user.ContactNumber = model.ContactNumber;
                    user.Email = model.Email;
                    user.RealName = model.RealName;

                    var updateResponse = uo.UpdateUserInfo(user);
                    if (updateResponse.IsSuccess)
                    {
                        return RedirectToAction("EditSuccess");
                    }
                    else
                    {
                        ModelState.AddModelError("", updateResponse.Message);
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Cannot Find the specific user.");
                }
            }

            return View(model);
        }

        public ActionResult EditSuccess()
        {
            return View();
        }
    }
}
